package com.kg.tombs.controller;

import com.kg.tombs.db.MongoVerticle;
import com.kg.tombs.service.AiService;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AiController {

    private final Vertx vertx;

    private final MongoVerticle mongoVerticle;

    private final AiService aiService;

    public AiController(Vertx vertx, MongoVerticle mongoVerticle) {
        this.vertx = vertx;
        this.mongoVerticle = mongoVerticle;
        this.aiService = new AiService(vertx, mongoVerticle);
    }

    public void ask(RoutingContext ctx) {
        JsonObject body = ctx.getBodyAsJson();
        String question = null;
        String collection = null;
        if (body != null) {
            question = body.getString("question");
            collection = body.getString("collection");
        }
        aiService.ask(collection, question)
                .onSuccess(result -> ctx.response()
                        .putHeader("Content-Type", "application/json")
                        .end(result.encode()))
                .onFailure(err -> {
                    log.error("AI问答错误: ", err);
                    sendError(ctx, 500, "AI服务暂时不可用: " + err.getMessage());
                });
    }

    private void sendError(RoutingContext ctx, int statusCode, String message) {
        ctx.response()
                .setStatusCode(statusCode)
                .putHeader("Content-Type", "application/json")
                .end(new JsonObject().put("error", message).encode());
    }
}
